package util;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库连接工具类
 *   - 提供获取连接和关闭连接方法
 */
public class JDBCUtils {
    //数据源
    private static DataSource dataSource = null;

    //配置连接信息
    static {
        try{
            //1.加载配置文件
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(is);
            //2.读取配置文件信息
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            //3.配置数据源
            dataSource = new MysqlDataSource();
            MysqlDataSource mysqlDataSource = (MysqlDataSource) dataSource;
            mysqlDataSource.setUser(user);
            mysqlDataSource.setPassword(password);
            mysqlDataSource.setURL(url);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }


    /**
     * 关闭数据库连接
     * @param conn 连接对象
     */
    public static void closeConnection(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭数据库连接等资源
     * @param ps
     * @param conn
     */
    public static void closeResource(PreparedStatement ps,Connection conn){
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public static void closeResource(ResultSet rs,PreparedStatement ps,Connection conn){
        closeResource(ps,conn);
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //测试
    public static void main(String[] args) throws SQLException {
        System.out.println(JDBCUtils.getConnection());
    }
}
